package com.homwee.tvap.common.comSettingInterface;

import java.io.File;
import java.util.ArrayList;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
//zcj 2018-10-31 import android.os.SystemProperties;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.homwee.factory.FactoryActivity;
import com.homwee.factory.FactoryModeMenu;
import com.homwee.factory.FactoryToast;
import com.homwee.factory.ShowFactoryTipsService;
import com.homwee.factory.util.Contants;
//zcj 2018-10-30import com.changhong.tvos.service.TvFactoryManager;
//zcj 2018-10-30import com.changhong.tvos.service.TvMiscManager;
//import android.content.pm.IPackageDataObserver;
//import com.changhong.dmt.system.miscservice.CHMiscServiceBinder;
//import com.changhong.tvos.common.MiscManager;
//import com.changhong.tvos.common.SystemManager;
//import com.changhong.tvos.common.TVManager;
//import com.changhong.tvos.common.exception.TVManagerNotInitException;
//import com.changhong.tvos.service.TvMiscManager;
import com.mediatek.twoworlds.factory.MtkTvFApiDisplayTest;
import com.mediatek.twoworlds.factory.MtkTvFApiInformation;
import com.mediatek.twoworlds.factory.MtkTvFApiSystem;
import com.mediatek.twoworlds.factory.common.MtkTvFApiSystemTypes;
import com.homwee.tvap.common.ap.ComSettingManager;
import com.mediatek.twoworlds.tv.MtkTvUtil;
import com.android.internal.app.LocalePicker;
import com.mediatek.twoworlds.tv.common.MtkTvConfigType;
import com.mediatek.twoworlds.tv.common.MtkTvConfigTypeBase;
import android.net.wifi.WifiManager;
import java.util.Locale;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;
import android.net.wifi.WifiConfiguration;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothAdapter;
import com.mediatek.twoworlds.tv.common.MtkTvConfigTypeBase.*;
import com.android.internal.app.LocalePicker;
import com.mediatek.twoworlds.tv.MtkTvConfig;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothAdapter;
import com.homwee.factory.R;


import com.mediatek.wwtv.tvcenter.util.SaveValue;

//page 7
public class factoryPage7 {

	public static final String ACTION_REQUEST_SHUTDOWN = "android.intent.action.ACTION_REQUEST_SHUTDOWN";

	public static final String EXTRA_KEY_CONFIRM = "android.intent.extra.KEY_CONFIRM";

	private Context mContext = null;
	private FactoryActivity mFactoryActivity = null;
	static factoryPage7 Interface = null;
	static boolean isResetStart = false;
	List<LocalePicker.LocaleInfo> localeInfoList;
    //static String mBrand = android.os.Build.BRAND;
	MtkTvFApiDisplayTest mMtkTvFApiDisplayTest = null;
	MtkTvUtil mMtkTvUtil = null;
	MtkTvFApiSystem mMtkTvFApiSystem = null;
	//private SaveValue mSaveValue=null;
	private MtkTvConfig mTvConfig = MtkTvConfig.getInstance();
	MenuConfigManager mCfg = MenuConfigManager.getInstance(null);
	final String mBrand=android.os.Build.BRAND;
	final String mProductName= Build.PRODUCT;
	final String TAG="CHFactory.factoryPage7";
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Log.d("zcj", "msg" + msg.what);
			//showTip();

			super.handleMessage(msg);
            //if(mBrand.equalsIgnoreCase("Philco")){
			// callSystemShutDown();
            //            } else {
			if(checkFactoryReset()) {
				showTip();
			}else{
				showResetToast("something wrong in factory reset,please reset aging");
				MtkTvUtil.IRRemoteControl(3);
				isResetStart = false;
			}
			 //callSystemShutDown();
           //             }
		}

	};

	private factoryPage7(Context context) {
		// TVManager tvManager = TVManager.getInstance(context);
		try {
			// zcj 2018-10-30mTvMiscManager = TvMiscManager.getInstance();
			// zcj 2018-10-30mTvFactoryManager = TvFactoryManager.getInstance();
			// miscManager = tvManager.getMiscManager();
			// mSystemManager =tvManager.getSystemManager();
			mMtkTvFApiDisplayTest = MtkTvFApiDisplayTest.getInstance();
			mMtkTvUtil = MtkTvUtil.getInstance();
			mMtkTvFApiSystem=MtkTvFApiSystem.getInstance();
			mContext = context;
			mFactoryActivity = (FactoryActivity) context;
			//mSaveValue=SaveValue.getInstance(context);
			Log.v("CHFactory.factoryPage7","factorypage7 init");
		} catch (Exception e) {
			// TODO: handle exception
			Log.v("tv", "miscManager ==null");
		}
	}

	public static factoryPage7 getInstance(Context context) {
		if (Interface == null) {
			Interface = new factoryPage7(context);
		}
		return Interface;
	}

	public boolean setMask(String mask) {
		byte[] imask = new byte[1];
		if (mask.equalsIgnoreCase("0")) {
			imask[0] = 0;
		} else {
			imask[0] = 1;
		}
		// zcj 2018-10-30mTvMiscManager.writeEepDataByName("devFlag", imask);
		return true;
	}

	public void systemInit() {
		Log.v("tv", "systemInit start");
		Log.d("zcj", "isResetStart" + (isResetStart ? "true" : "false"));
		if (isResetStart == false) {
			isResetStart = true;

			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mMtkTvFApiDisplayTest.setBurningMode(false);
					mMtkTvFApiSystem.setUartEnvironment(false);
					resetini();
					resetAutoEnterFactoryIni();
					if (mBrand.equals("Philco") && mProductName.contains("ISDB")) {
						mMtkTvFApiSystem.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_DIRECT);
						cleanApp(false);
					}
					else{
						factoryResetPowerMode();
						cleanApp(true);
					}
					Log.v("tv", "systemInit start resetTVOSIntSettings end");
				}
			}).start();
		}

		Log.v("tv", "systemInit end");
	}


	public void quickSystemInit() {
		Log.v("tv", "systemInit start");
		Log.d("zcj", "isResetStart" + (isResetStart ? "true" : "false"));
		if (isResetStart == false) {
			isResetStart = true;

			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mMtkTvFApiDisplayTest.setBurningMode(false);
					mMtkTvFApiSystem.setUartEnvironment(false);
					//mMtkTvFApiSystem.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY);
					factoryResetPowerMode();
					resetini();
					//setTvUserSetupComplete();
//					if(mBrand.equalsIgnoreCase("Philco")){
//					mMtkTvFApiSystem.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_DIRECT);
//					//SaveValue.saveWorldValue(context,"MAIN_INPUT_TYPE",11,false);
//
//					resetFactoryData();
//					cleanWifiConfiguredNetworks();
//					removePairDevice();
//					setTvUserSetupComplete();
//					mMtkTvUtil.resetFac();
//					mHandler.sendEmptyMessageDelayed(0, 7000);
//					//cleanApp(false);
//					} else {
//					mMtkTvFApiSystem.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY);
					//cleanApp(true);
					//SaveValue.saveWorldValue(context,"MAIN_INPUT_TYPE",11,false);
					
					cleanWifiConfiguredNetworks();
					removePairDevice();
					resetFactoryData();
					setTvUserSetupComplete();
					resetAutoEnterFactoryIni();
					mMtkTvUtil.resetFac();
					mHandler.sendEmptyMessageDelayed(0, 7000);
					//}
					//mMtkTvUtil.resetFac();
					//mHandler.sendEmptyMessageDelayed(0, 300);
					// callSystemShutDown();
					Log.v("tv", "systemInit start resetTVOSIntSettings end");
				}
			}).start();
		}

		Log.v("tv", "systemInit end");
	}

	private void setTvUserSetupComplete() {
		try {
			Settings.Secure.putInt(mContext.getContentResolver(),
					"tv_user_setup_complete", 0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					"user_setup_complete", 0);
			Settings.Secure.putString(mContext.getContentResolver(),
					"last_setup_shown", "");
			//set default language country
			Settings.Secure.putInt(mContext.getContentResolver(),
					"ch_defaultLanguage",0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					"ch_defaultCountry",0);
			
			Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0);

			PackageManager pm = mContext.getPackageManager();
			ComponentName componentName = new ComponentName(
					"com.google.android.tungsten.setupwraith",
					"com.google.android.tungsten.setupwraith.MainActivity");

			pm.setComponentEnabledSetting(componentName,
					PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
		}catch (Exception e){
			Log.d("CHFactory.setTvUserSetupComplete","Exception in setTvUserSetupComplete");
			e.printStackTrace();
		}

	}

        private void resetFactoryData(){
            localeInfoList = LocalePicker.getAllAssetLocales(mContext, false);
            Settings.Global.putInt(
                mContext.getContentResolver(), "no_signal_auto_power_off", 0);
            Settings.Global.putInt(
                mContext.getContentResolver(), "power_switch_off_timer", 0);
            Settings.System.putInt(mContext.getContentResolver(), "screen_off_timeout", 300000);
            Settings.Secure.putInt(mContext.getContentResolver(), "sleep_timeout", -1);
			Settings.Global.putInt(mContext.getContentResolver(), "hdmi_control_enabled", 0);
			Settings.Global.putInt(mContext.getContentResolver(), "hdmi_control_auto_device_off_enabled", 0);
			Settings.Global.putInt(mContext.getContentResolver(), "hdmi_control_auto_wakeup_enabled", 0);
			Settings.Global.putInt(mContext.getContentResolver(), "hdmi_arc_control_enabled", 1);
           ComSettingManager.getInstance(mContext).getFactory().setVolume(25);

	   final Calendar now = Calendar.getInstance();
	   TimeZone tz = TimeZone.getTimeZone("GMT-3");
	   now.setTimeZone(tz);

           //if(mBrand.equalsIgnoreCase("Philco")){
           //for(LocalePicker.LocaleInfo lr: localeInfoList){
           //   if(lr.getLocale().getLanguage().equalsIgnoreCase("pt")){
           //       LocalePicker.updateLocale(lr.getLocale());
			//      break;
           //   }
           //}
           //Settings.Secure.putInt(mContext.getContentResolver(), "countryIndex", 2);
           //MtkTvConfig.getInstance().setCountry(MtkTvConfigTypeBase.S3166_CFG_COUNT_BRA);
           //} else {
           for(LocalePicker.LocaleInfo lr: localeInfoList){
              if(lr.getLocale().getLanguage().equalsIgnoreCase("en")){
                  LocalePicker.updateLocale(lr.getLocale());
                  break;
              }
           }
           Settings.Secure.putInt(mContext.getContentResolver(), "countryIndex", 0);
           MtkTvConfig.getInstance().setCountry(MtkTvConfigTypeBase.S3166_CFG_COUNT_ARG);
           //}
            
                
        } 

	public void resetini() {
		MtkTvFApiInformation.getInstance().setIniParameter(
				Contants.PATH_FACTORYINI, Contants.FACTORY_M_MODE, "0");
		MtkTvFApiInformation.getInstance().setIniParameter(
				Contants.PATH_FACTORYINI, Contants.FACTORY_AGE_MODE, "0");
		MtkTvFApiInformation.getInstance().setIniParameter(
				Contants.PATH_FACTORYINI, Contants.KEY_UPGRADE_FORCE, "0");
		MtkTvFApiInformation.getInstance().setIniParameter(
				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_TVWORKTIME, "NG");
		MtkTvFApiInformation.getInstance().setIniParameter(
				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_SKIP_WIZARDSETUP, "0");
        Settings.System.putInt(mContext.getContentResolver(), Contants.FACTORY_M_MODE_GO, 0);

		if(mBrand.equals("Philco")&&mProductName.contains("ISDB")){
			MtkTvFApiInformation.getInstance().setIniParameter(
					Contants.PATH_FACTORYINI, Contants.FACTORY_FIRST_POWERON, "1");
		}

	}

	public void showTip() {
		FactoryModeMenu.refresh(mContext);
		Intent TVtoolServiceIntent = new Intent(mContext,
				ShowFactoryTipsService.class);
		TVtoolServiceIntent
				.setAction("ShowFactoryTipsService");
		mContext.startService(TVtoolServiceIntent);
	}

	private void callSystemShutDown() {
		/*
		 * Intent i = new Intent(ACTION_REQUEST_SHUTDOWN);
		 * i.putExtra(EXTRA_KEY_CONFIRM, false);
		 * i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(i);
		 */

		PowerManager mPowerManager = (PowerManager) mContext
				.getSystemService(Context.POWER_SERVICE);
		// mPowerManager.shutdown(false, "shutdown", false);

	}

	private boolean clearUserDatas() {
		String[] unClearApps = { "com.changhong.factory" };

		File root = new File("/data/data/");
		ArrayList<String> delApps = new ArrayList<String>();
		if (root != null) {
			String[] strs = root.list();
			if (strs != null && strs.length > 0) {
				for (String str : strs) {
					if (!str.startsWith("com.android")
							&& !(isStringInList(str, unClearApps))) {
						delApps.add(str);
						// Log.v("tv","delApps add ="+str);
					} else if (str.startsWith("com.android.provider")
							|| str.startsWith("com.android.browser")) {
						delApps.add(str);
						// Log.v("tv","delApps add ="+str);
					}
				}
			}
			if (!delApps.isEmpty()) {
				try {
					ActivityManager am = (ActivityManager) mContext
							.getSystemService(Context.ACTIVITY_SERVICE);
					ClearUserDataObserver observer = new ClearUserDataObserver();
					for (String str2 : delApps) {
						Log.v("tv", "start clear =" + str2);
						// am.clearApplicationUserData(str2, observer);
					}
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
				return true;
			}
		}
		return false;
	}

	private boolean isStringInList(String str, String[] list) {
		if (str == null || list == null || list.length <= 0)
			return false;
		for (String strList : list) {
			if (strList.equals(str)) {
				return true;
			}
		}
		return false;
	}

	public void systemClearApp() {
		if (isResetStart == false) {
			isResetStart = true;

			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mMtkTvFApiDisplayTest.setBurningMode(false);
					mMtkTvFApiSystem.setUartEnvironment(false);
					//mMtkTvFApiSystem.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY);
					factoryResetPowerMode();
					resetini();
					//setTvUserSetupComplete();
					cleanApp(true);
					//mMtkTvUtil.resetFac();
					//mHandler.sendEmptyMessageDelayed(0, 300);
					// callSystemShutDown();
					Log.v("tv", "systemInit start resetTVOSIntSettings end");
				}
			}).start();
		}

		Log.v("tv", "systemInit end");
	}

	class ClearUserDataObserver {// extends IPackageDataObserver.Stub {
		public void onRemoveCompleted(final String packageName,
				final boolean succeeded) {
			Log.v("tv", "Clear " + packageName + succeeded);
		}
	}

	private void clearUserDataExt() {
		try {
			String NETWORK_SELECT = "PROV_network_Select";
			String NETWORK_WIRELESS_SWITCH = "PROV_network_wirless_onoff";
			String NETWORK_IPSET_TYPE = "PROV_network_ipset_type";
			String OBONI_SCREENSAVER_NOSOURCE = "PROV_Oboni_screenSaver_nosource";
			String OBONI_EYE_TIP = "PROV_Oboni_eye_tip";
			String SYSTEM_POWERONMUSIC = "SYSTEM_POWERONMUSIC";// ������������Ϊ��

			String NETWORK_DIAL_FUNCTION = "PROV_network_dial_function";
			String NETWORK_DIAL_ACCOUNT = "PROV_network_dial_account";
			String NETWORK_DIAL_PASSWORD = "PROV_network_dial_password";
			String NETWORK_DIAL_AUTO = "PROV_network_dial_auto";

			Settings.Secure.putString(mContext.getContentResolver(),
					"ActiveDate", "");
			Settings.Secure.putInt(mContext.getContentResolver(),
					"logcat_reader", 0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					NETWORK_SELECT, 0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					NETWORK_WIRELESS_SWITCH, 0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					NETWORK_IPSET_TYPE, 0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					OBONI_SCREENSAVER_NOSOURCE, 1);
			Settings.Secure.putInt(mContext.getContentResolver(),
					OBONI_EYE_TIP, 0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					SYSTEM_POWERONMUSIC, 1);

			Settings.Secure.putInt(mContext.getContentResolver(),
					NETWORK_DIAL_FUNCTION, 0);
			Settings.Secure.putInt(mContext.getContentResolver(),
					NETWORK_DIAL_AUTO, 0);
			Settings.Secure.putString(mContext.getContentResolver(),
					NETWORK_DIAL_ACCOUNT, "");
			Settings.Secure.putString(mContext.getContentResolver(),
					NETWORK_DIAL_PASSWORD, "");

			// //DataAcceser dataAcc = DataAcceser.getInstance(this);
			// dataAcc.saveIntValue(CoreDef.NETWORK_SELECT,
			// SSDef.DEFAULT_NETWORK_TYPE);
			// dataAcc.saveIntValue(CoreDef.NETWORK_WIRELESS_SWITCH, 0);
			// dataAcc.saveIntValue(CoreDef.NETWORK_IPSET_TYPE, 0);
			// dataAcc.saveIntValue(CoreDef.OBONI_SCREENSAVER_NOSOURCE, 1);
			// dataAcc.saveIntValue(CoreDef.OBONI_EYE_TIP, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void delete(File file) {
		if (file.isFile()) {
			file.delete();
			return;
		}

		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				delete(childFiles[i]);
			}
			file.delete();
		}
	}

	public void cleanApp(boolean isShutDown) {
		// TODO Auto-generated method stub
		/*Intent resetIntent = new Intent();
		resetIntent.setComponent(new ComponentName("com.android.tv.settings",
				"com.android.tv.settings.device.storage.ResetActivity"));
		mContext.getApplicationContext().startActivity(resetIntent);*/


		Intent resetIntent = new Intent("android.intent.action.FACTORY_RESET");
		resetIntent.setPackage("android");
		resetIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
		resetIntent.putExtra("android.intent.extra.REASON", "ResetConfirmFragment");
		resetIntent.putExtra("shutdown", isShutDown);

		mContext.getApplicationContext().sendBroadcast(resetIntent);
	}

	public void cleanApp(Context context) {
		// TODO Auto-generated method stub
		Intent resetIntent = new Intent();
		resetIntent.setComponent(new ComponentName("com.android.tv.settings",
				"com.android.tv.settings.device.storage.ResetActivity"));
		context.startActivity(resetIntent);
	}

	/** add for preset client Channel */
	public void systemInitForPresetClientChannel() {
		Log.v("tv", "systemInit start");
		if (isResetStart == false) {
			isResetStart = true;

			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub

					Log.v("tv", "systemInit start resetTVOSIntSettings");

					try {
						File f = new File("/data/dtv/changhong_tvos_dtv.db");
						if (f.exists()) {
							f.delete();
						}
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}

					Runtime mRuntime = Runtime.getRuntime();
					/*
					 * try {
					 * mRuntime.exec("rm -f /tvdatabase/Database/dtv_cmdb_0.bin"
					 * );
					 * mRuntime.exec("rm -f /tvdatabase/Database/dtv_cmdb_1.bin"
					 * );
					 * mRuntime.exec("rm -f /tvdatabase/Database/dtv_cmdb_2.bin"
					 * );
					 * mRuntime.exec("rm -f /tvdatabase/Database/atv_cmdb.bin");
					 * mRuntime
					 * .exec("rm -f /tvdatabase/Database/atv_cmdb_cable.bin");
					 * mRuntime
					 * .exec("rm -f /tvdatabase/Database/dtv_cmdb_ml_air.bin");
					 * mRuntime
					 * .exec("rm -f /tvdatabase/Database/dtv_cmdb_ml_cable.bin"
					 * ); } catch (IOException e) { // TODO Auto-generated catch
					 * block e.printStackTrace(); }
					 */

					/* add for TREEVIEW */
					/*
					 * //zcj 2018-10-31 if
					 * (("TREEVIEW".equalsIgnoreCase(Build.BRAND)) ||
					 * ("CHINTERUAE".equalsIgnoreCase(Build.BRAND)) ||
					 * ("CHMESAUDI".equalsIgnoreCase(Build.BRAND))) { if (new
					 * File("/tvcustomer/Customer", "boot0_old.jpg") .exists())
					 * { try { mRuntime.exec(
					 * "busybox cp /tvcustomer/Customer/boot0_old.jpg /tvcustomer/Customer/boot0.jpg -rf"
					 * );
					 * mRuntime.exec("rm /tvcustomer/Customer/boot0_old.jpg");
					 * mRuntime.exec("sync"); } catch (IOException e) {
					 * e.printStackTrace(); } } add for boot renew if (new
					 * File("/chperm/logo/media0",
					 * "novideo_bootlogo_old.png").exists()) { try {
					 * mRuntime.exec(
					 * "busybox cp /chperm/logo/media0/novideo_bootlogo_old.png /chperm/logo/media0/novideo_bootlogo.png -rf"
					 * ); mRuntime.exec(
					 * "rm/chperm/logo/media0/novideo_bootlogo_old.png");
					 * mRuntime.exec("sync"); } catch (IOException e) { // TODO
					 * e.printStackTrace(); } } if (new
					 * File("/data/logo/media4/").exists()) { try {
					 * SystemProperties.set("sys.logo.set.usersel", "0");
					 * SystemProperties .set("sys.logo.set.status", "4");
					 * mRuntime.exec("rm /data/logo/media4 -rf");
					 * mRuntime.exec("sync"); } catch (IOException e) {
					 * e.printStackTrace(); } }
					 * SystemProperties.set("persist.sys.welcome.text", "");
					 * SystemProperties.set("persist.sys.welcome.backcolor",
					 * "0");
					 * SystemProperties.set("persist.sys.welcome.textcolor",
					 * "255,255,255");
					 * SystemProperties.set("persist.sys.welcome.textsize",
					 * "64"); }
					 */
					/* add for HIFI end */
					Settings.System.putInt(mContext.getContentResolver(),
							"persist.sys.wow", 0);

					// CHMiscServiceBinder mChMiscServiceBinder
					// =CHMiscServiceBinder.getInstance(mContext);
					// mChMiscServiceBinder.getPanelMisc().doUserReset(1);
					// add 2018-5-17
					Settings.Global.putString(mContext.getContentResolver(),
							"Disclaimer", "disagree");
					// 0:工厂出厂设置 1：用户保留安装应用 2：用户删除已安装应用
					/*
					 * try { //zcj 2018-10-30
					 * mTvMiscManager.SetTvDetectEnable(false); //zcj 2018-10-30
					 * mTvMiscManager.setFactoryMode(false); //zcj 2018-10-30
					 * mTvFactoryManager.setAgingMode_ONOFF(0); //zcj 2018-10-30
					 * mTvMiscManager.resetFactory(3); } catch (RemoteException
					 * e) { // TODO Auto-generated catch block
					 * e.printStackTrace(); }
					 */
					// mChMiscServiceBinder.getPanelMisc().doUserReset(0);
					// mChMiscServiceBinder.getUsbDevices().doRFDongleUIDReset(0);
					setMask("1");
					// mSystemManager.resetTVOSIntSettings(0);
					Log.v("tv", "systemInit start resetTVOSIntSettings end");
				}
			}).start();
		}
	}

	/** SET MEMC **/
	public void setMemcIndex(int mMemcEffectindex){
		mTvConfig.setConfigValueForAllElements(MtkTvConfigTypeBase.CFG_VIDEO_VID_MJC_EFFECT, mMemcEffectindex);
	}
	public int getMemcIndex(){
		int mMemcEffectindex = mTvConfig.getConfigValue(MtkTvConfigTypeBase.CFG_VIDEO_VID_MJC_EFFECT);
		return mMemcEffectindex;
	}
	public int resetMemc(){
		mTvConfig.setConfigValue(MtkTvConfigTypeBase.CFG_VIDEO_VID_MJC_EFFECT, 0, MtkTvConfigTypeBase.CFGF_SET_DEFAULT_VALUE);
		int mMemcEffectindex = mTvConfig.getConfigValue(MtkTvConfigTypeBase.CFG_VIDEO_VID_MJC_EFFECT);
		return mMemcEffectindex;
	}

	/** FOR QUICKRESET TO SET INI **/
	public void setContext(Context context){
		mContext = context;
	}

	public List<WifiConfiguration> cleanWifiConfiguredNetworks() {
		WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
		List<WifiConfiguration> configuredNetworks = wifiManager
				.getConfiguredNetworks();

		for (int i = 0; i < configuredNetworks.size(); i++) {
			wifiManager.removeNetwork(configuredNetworks.get(i).networkId);
		}
		return configuredNetworks;
	}




	public void removePairDevice(){
		Settings.Global.putString(mContext.getContentResolver(), "ch_display","");
		Settings.Global.putInt(mContext.getContentResolver(),"ch_bluetooth",1);
		BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if(mBluetoothAdapter != null){
			Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
			for(BluetoothDevice device : bondedDevices ){
				unpairDevice(device);
			}
		}

	}


	public boolean unpairDevice(BluetoothDevice device) {

		if (device != null) {
			int state = device.getBondState();

			if (state == BluetoothDevice.BOND_BONDING) {
				device.cancelBondProcess();
			}

			if (state != BluetoothDevice.BOND_NONE) {
				final boolean successful = device.removeBond();
				if (successful) {
					Log.d("zcj", "Bluetooth device successfully unpaired: " + device.getName());
					return true;
				} else {
					Log.e("zcj", "Failed to unpair Bluetooth Device: " + device.getName());
				}
			}
		}
		return false;
	}


	public void resetAutoEnterFactoryIni(){
		String enterFactoryDb=MtkTvFApiInformation.getInstance().getIniParameter(
				Contants.PATH_FACTORY_AUTOENTERFACTORY_INI, "FactoryDB:DB");
		if(enterFactoryDb.equals("1")){
			int ret=MtkTvFApiInformation.getInstance().setIniParameter(
					Contants.PATH_FACTORY_AUTOENTERFACTORY_INI, "FactoryDB:DB","0");
		}
	}

	public void showResetToast(){
		FactoryToast toast = new FactoryToast(mContext);
		toast.setDuration(500);
		toast.setToastIcon(R.drawable.pic_eye);
		toast.setMessage(mContext.getString(R.string.factory_system_reset));
		toast.getTextView().getBackground().setAlpha(200);
		toast.show();
	}

	public String getAutoEnterFactory(){
		String enterFactoryDb=MtkTvFApiInformation.getInstance().getIniParameter(
				Contants.PATH_FACTORY_AUTOENTERFACTORY_INI, "FactoryDB:DB");
		return enterFactoryDb;
	}
	public void setAutoEnterFactory(String value){
		MtkTvFApiInformation.getInstance().setIniParameter(
				Contants.PATH_FACTORY_AUTOENTERFACTORY_INI, "FactoryDB:DB", value);
	}


	private boolean checkFactoryReset(){
		resetini();

		boolean ret = true;
		ret&=checkPowerMode();
		ret&= MtkTvFApiInformation.getInstance().getIniParameter(
				Contants.PATH_FACTORYINI, Contants.FACTORY_M_MODE) != "1";
		Log.d(TAG,"checkFactoryReset ret1="+ret);

		int maxcount = 3;
		for (int i = 0; i < maxcount && !ret; i++) {
			MtkTvFApiInformation.getInstance().setIniParameter(
					Contants.PATH_FACTORYINI, Contants.FACTORY_M_MODE, "0");
			boolean ret2 = MtkTvFApiInformation.getInstance().getIniParameter(
					Contants.PATH_FACTORYINI, Contants.FACTORY_M_MODE) != "1";
			factoryResetPowerMode();
			checkPowerMode();
		}

		return ret;
	}

	public void showResetToast(String str){
		FactoryToast toast = new FactoryToast(mContext);
		toast.setDuration(500);
		toast.setToastIcon(R.drawable.pic_eye);
		toast.setMessage(str);
		toast.getTextView().getBackground().setAlpha(200);
		toast.show();
	}
	public int getIniFactoryPowerMode(){
		int powerMode=1;//SECONDARY
		String modeStr = MtkTvFApiInformation
				.getInstance()
				.getIniParameter(Contants.PATH_CUSTOM_FUNC_INI,
						Contants.FACTORY_RESET_POWERMODE);
		if(!TextUtils.isEmpty(modeStr)){
			powerMode=Integer.parseInt(modeStr);
		}
		return powerMode;
	}
	public void factoryResetPowerMode(){
		int powerMode=getIniFactoryPowerMode();
		Log.d(TAG,"factoryResetPowerMode: "+powerMode);
		switch(powerMode) {
			case 0:
				mMtkTvFApiSystem
						.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_DIRECT);
				break;
			case 1:
				mMtkTvFApiSystem
						.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY);
				break;
			case 2:
				mMtkTvFApiSystem
						.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_MEMORY);
				break;
			default:
				mMtkTvFApiSystem
						.setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY);
				break;
		}
	}
	public boolean checkPowerMode(){
		MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode curPowerMode=mMtkTvFApiSystem.getFactoryPowerMode();
		MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode cmpPowerMode;
		int powerMode=getIniFactoryPowerMode();
		Log.d(TAG,"checkPowerMode: "+powerMode);
		switch(powerMode) {
			case 0:
				cmpPowerMode=MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_DIRECT;
				break;
			case 1:
				cmpPowerMode=MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY;
				break;
			case 2:
				cmpPowerMode=MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_MEMORY;
				break;
			default:
				cmpPowerMode=MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY;
				break;
		}
		return curPowerMode==cmpPowerMode?true:false;
	}
	public static boolean isIsResetStart() {
		return isResetStart;
	}
}